<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use app\middleware\Check;

/**
 * Class 微信授权 用户端
 * @package app\controller
 */
class Wxlogin extends BaseController
{
    /**
     * 微信授权登录
     */
    public function login()
    {
        $state = $this->request->param('state');//原样参数返回..
        require_once '../sdk/WxpayAPI/lib/WxPay.Config.php';
        $appid  =\WxPayConfig::APPID;
        $apiurl = "http://dxsd.jlxmall.com/";
        return header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$apiurl."Wxlogin/callback&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect");
    }
    /**
     * @desc 微信授权回调接口地址
     */
    public function callback() {
        // 获取Access_token
        $state = $this->request->param('state','');//原样参数返回..
        $code = $this->request->param('code');//code
        if($code){
            require_once '../sdk/WxpayAPI/lib/WxPay.Config.php';
            $appid  =\WxPayConfig::APPID;
            $secret = \WxPayConfig::APPSECRET;
            $param["code"] = $code;
            $param["grant_type"] = "authorization_code";
            $param["appid"] = $appid;
            $param["secret"] = $secret;
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?".http_build_query($param);
            $data = $this->curl_url($url);
            if(property_exists($data,'errcode')){
                return $data;
            }else{
                $user_data = $this->get_userinfo($data->openid,$data->access_token,$data->refresh_token);
//                $arry['code'] = $state;
//                $arry['openid'] = $user_data['openid'];
//                $arry['username'] = $user_data['username'];
//                $arry['portrait'] = $user_data['portrait'];
                $game_url = "http://dxsd.jlxmall.com/userplat?".'code='.$state.'&openid='.$user_data['openid'];
                header("location:$game_url");
            }
        }else{
            return jsonFail('获取Authorization_Code失败');
        }
    }
    //微信授权回调根据Access_token获取指定用户信息
    public function get_userinfo($openid,$access_token,$refresh_token){
        if($access_token){
            $param["openid"] = $openid;
            $param["access_token"] = $access_token;
            $url = "https://api.weixin.qq.com/sns/userinfo?".http_build_query($param);
            $data = $this->curl_url($url);
            return  $this->logins($data->openid,$data->nickname,$data->headimgurl,$access_token,$refresh_token);
        }
    }
    //获取配置信息
    public function logins($userid,$uname,$portrait,$access_token,$refresh_token) {
        $data['openid'] = $userid;   // 账号参数
        $data['username'] = $uname;   // 用户名
        $data['portrait'] = $portrait;   // 头像访问
        $data['access_token'] = $access_token;   // access_token码，一个月有效期
        $data['refresh_token'] = $refresh_token;//access_token码过期后，刷新码，10年有效期
        $data['create_time'] = time();   // 时间戳
        $user_data = Db::table('eb_user')->where('openid',$data['openid'])->find();
        if(empty($user_data)){
            try {
                $res =  Db::table('eb_user')->insert([
                    'openid'=> $data['openid'],
                    'username'=>$data['username'],
                    'portrait'=>$data['portrait'],
                    'access_token'=>$data['access_token'],
                    'refresh_token' =>$data['refresh_token'],
                    'create_time'=>time(),
                ]);
            } catch (\Exception $e) {
                return jsonFail('服务器从错误~');
            }
        }
        return $data;
    }
    //curl进行Https Get访问链接
    public function curl_url($url){
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $output = curl_exec($ch); //执行并获取HTML文档内容
        $data = json_decode($output);
        //释放curl句柄
        curl_close($ch);
        return  $data;
    }
}
